<template>
  <div>
    <!-- 添加或修改spu -->
    <el-form label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="(tm, index) in tradeMarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          placeholder="描述"
          type="textarea"
          rows="4"
          v-model="spu.description"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handlerSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}个未选择`"
          v-model="attrIdAndAttrName"
        >
          <el-option
            :label="unSelect.name"
            :value="`${unSelect.id}:${unSelect.name}`"
            v-for="(unSelect, $index) in unSelectSaleAttr"
            :key="unSelect.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin-left: 10px"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <el-table border style="margin-top: 5px" :data="spu.spuSaleAttrList">
          <el-table-column
            label="序号"
            type="index"
            width="80px"
            align="center"
          ></el-table-column>
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值名称列表">
            <template slot-scope="{ row, $index }">
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.id"
                closable
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                :disable-transitions="false"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      //存储spu信息属性,注意在添加spu的时候没有发请求，收集数据的字段需要提前定义好
      spu: {
        category3Id: 0,
        description: "",
        spuName: "",
        tmId: '', //品牌id
        //spu图片信息
        spuImageList: [
          {
            id: 0,
            imgName: "",
            imgUrl: "",
            spuId: 0,
          },
        ],
        //平台属性与属性值
        spuSaleAttrList: [
        //   {
        //     baseSaleAttrId: 0,
        //     id: 0,
        //     saleAttrName: "",
        //     spuId: 0,
        //     spuSaleAttrValueList: [
        //       {
        //         baseSaleAttrId: 0,
        //         id: 0,
        //         isChecked: "",
        //         saleAttrName: "",
        //         saleAttrValueName: "",
        //         spuId: 0,
        //       },
        //     ],
        //   },
        ],

      },
      tradeMarkList: [], //存储品牌信息
      spuImageList: [], //存储spu图片数据
      saleAttrList: [], //销售属性数据
      attrIdAndAttrName:''   //收集未选择的销售属性id
    };
  },
  methods: {
    handleRemove(file, fileList) {
      //fileList是删除某一张图片后剩余的图片
      this.spuImageList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片上传成功的回调
    handlerSuccess(response,file,fileList){
        this.spuImageList = fileList;
    },
    //初始化SpuForm的数据
    async initSpuData(spu) {
      //获取spu信息数据
      let spuResult = await this.$api.spu.reqSpu(spu.id);
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      //获取品牌的信息
      let tradeMarkResult = await this.$api.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      //获取spu图片的数据
      let spuImageResult = await this.$api.spu.reqSpuImageList(spu.id);
      if (spuImageResult.code == 200) {
        let listArr = spuImageResult.data;
        //照片墙显示的file-list必须有name与url字段,所以遍历拿到的数组，对其增加这两个属性
        listArr.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = listArr;
      }
      //获取平台全部销售属性
      let SaleResult = await this.$api.spu.reqBaseSaleAttrList();
      if (SaleResult.code == 200) {
        this.saleAttrList = SaleResult.data;
      }
    },
    //添加新增销售属性
    addSaleAttr(){
        //对收集额数据分割
        const[baseSaleAttrId,saleAttrName] = this.attrIdAndAttrName.split(":");
        //向spuSaleAttrList里添加新的销售属性
        let newSaleAttr = {baseSaleAttrId,saleAttrName,spuSaleAttrValueList:[]};
        this.spu.spuSaleAttrList.push(newSaleAttr);
        //清空数组
        this.attrIdAndAttrName = '';
    },
    //添加按钮的回调,控制button和input切换
    addSaleAttrValue(row){
        this.$set(row,'inputVisible',true);
        this.$set(row,'inputValue','');
    },
    //el-input失去焦点
    handleInputConfirm(row){
        //解构出销售属性中收集的数据
        const {baseSaleAttrId,inputValue} = row;
        //属性值不能含空串
        if (inputValue.trim()=='') {
            this.$message.error("属性值不能为空");
            return
        }
        //属性值不能相同
       let result =  row.spuSaleAttrValueList.every(item => item.saleAttrValueName!=inputValue);
        if (!result) {
            this.$message.error("属性值不能重复");
            return
        }
        let newSaleAttrValue = {baseSaleAttrId,saleAttrValueName:inputValue};
        row.spuSaleAttrValueList.push(newSaleAttrValue);
        row.inputVisible = false;
    },
    //保存按钮回调
   async addOrUpdateSpu(){
        //整理参数，图片需要携带imgName imgUrl字段
        this.spu.spuImageList = this.spuImageList.map(item=>{
            return{
                imageName:item.name,
                imaageUrl:(item.response&&item.response.data)||item.url
            }
        });
      let result =  await this.$api.spu.reqAddOrUpdateSpu(this.spu);
     if (result.code==200) {
        this.$message.success("保存spu成功！")
        //回到场景0
        this.$emit('changeScene',{scene:0, flag:this.spu.id?'修改':'添加'});
     }
     //清除form数据
     Object.assign(this._data,this.$options.data())
    },
    //点击添加spu按钮的时候发的请求
   async addSpuData(category3Id){
    this.spu.category3Id = category3Id
              //获取品牌的信息
      let tradeMarkResult = await this.$api.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
            //获取平台全部销售属性
      let SaleResult = await this.$api.spu.reqBaseSaleAttrList();
      if (SaleResult.code == 200) {
        this.saleAttrList = SaleResult.data;
      }
    },
    //取消按钮的回调
    cancel(){
        //切换场景为0
        this.$emit('changeScene',{scene:0, flag:''});
        //清除form数据,Object.assign是es6中新增的方法可以合并对象
        //组件实例的this._data,可以操作data中国响应数据
        //this.$options当前组件的配置对象，配置对象函数执行，返回的响应式数据为空
        Object.assign(this._data,this.$options.data())
    }

  },
  computed:{
    //计算出还未选择的销售属性
    unSelectSaleAttr(){
        //数组过滤，从已有的数组中过滤出用户需要的元素，并且返回一个新的数组
       let result =  this.saleAttrList.filter((item) => {
            //every返回布尔值，对每一个元素调用回调函数
            return this.spu.spuSaleAttrList.every((item1) => {
                //如果所有的销售属性中，存在和已有的销售属性不相等的，返回true
                return item.name!=item1.saleAttrName;
            })
        })
        return result;
    }
  }
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
